package com.rongshu.view.home.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.os.Process;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;

import com.rongshu.R;
import com.rongshu.base.BuildConfig;
import com.rongshu.eventbus.JPushMessage;
import com.rongshu.eventbus.NavigationIconReplace;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.LoginUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.BaseFragment;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.home.bean.VersionUpdateResponse;
import com.rongshu.view.home.contract.LoginExpView;
import com.rongshu.view.home.fragment.DiscoveryFragment;
import com.rongshu.view.home.fragment.PenpalFragment;
import com.rongshu.view.home.fragment.TodayRecommendFragment;
import com.rongshu.view.home.fragment.UserInfoFragment;
import com.rongshu.view.home.presenter.LoginExpPresenter;
import com.rongshu.view.submitArticle.activity.SubmitArticleActivity;
import com.rongshu.view.userInfo.entity.MessageInfo;
import com.rongshu.view.web.LocalWebActivity;
import com.rongshu.widget.VersionUpdateDialog;
import com.rongshu.widget.bottomBar.BottomBarItem;
import com.rongshu.widget.bottomBar.BottomBarLayout;
import com.umeng.socialize.UMShareAPI;
import com.utils.ApkUtils;
import com.utils.LogUtil;
import com.utils.SPUtils;
import com.utils.constants.SPKey;
import com.widget.guideview.NewbieGuide;
import com.widget.guideview.model.GuidePage;
import com.widget.guideview.model.HighLight;
import com.zzhoujay.richtext.RichText;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

import static com.rongshu.utils.UserInfoUtils.getUserId;

public class HomeActivity extends BaseActivity<LoginExpPresenter> implements LoginExpView {
    @BindView(R.id.fl_container)
    FrameLayout container;
    @BindView(R.id.bottom_option)
    BottomBarLayout bottomOption;
    @BindView(R.id.main_layout)
    RelativeLayout main;
    @BindView(R.id.submit_article)
    BottomBarItem submitArticle;
    //   为每个fragment设置标签
    private String[] tags = new String[]{"TodayRecommendFragment", "DiscoveryFragment", "PenpalFragment", "UserFragment"};
    private BaseFragment mTodayRecommendFragment, mDiscoveryFragment, mPenpalFragment, mUserFragment;
    private BaseFragment mContent;//当前fragment
    private FragmentManager sfm;
    private int tabSelect = 0;
    //map
    private Map<String, Object> map = null;
    //是否滑动到第七页
    private boolean isSmoothToSevenPage;
    //旋转动画
    private RotateAnimation rotateAnimation = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        hintTitleBar();
        RichText.initCacheDir(this);
        EventBus.getDefault().register(this);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_home;
    }

    @Override
    protected void initView() {
        loadFragment();
        //set presenter
        setPresenter(new LoginExpPresenter(this), this);
        bottomOption.setOnItemSelectedListener(new BottomBarLayout.OnItemSelectedListener() {
            @Override
            public void onItemSelected(final BottomBarItem bottomBarItem, int previousPosition, int currentPosition) {
                //投稿positon == 2,投稿选项点击不加载fragment
                switch (currentPosition) {
                    case 0:
                        tabSelect = currentPosition;
                        switchFragment(mContent, mTodayRecommendFragment, currentPosition);
                        break;
                    case 1:
                        tabSelect = currentPosition;
                        switchFragment(mContent, mDiscoveryFragment, currentPosition);
                        break;
                    case 2:
                        boolean preferences = SPUtils.getPreferences(SPKey.AGERR_AGREEMENT, false);
                        if (UserInfoUtils.getUserInfo() != null) {
                            if (preferences) {
                                Intent intent = new Intent(HomeActivity.this, SubmitArticleActivity.class);
                                startActivity(intent);
                            } else {
                                Intent intent = new Intent(HomeActivity.this, LocalWebActivity.class);
                                intent.putExtra(Constant.INTENT_TITLE, "投稿须知");
                                intent.putExtra(Constant.INTENT_H5, Common.SUBMIT_ARTICLE_NOTICE);
                                startActivity(intent);
                            }
                        } else {
                            LoginUtils.toLogin(HomeActivity.this);
                        }
                        break;
                    case 3:
                        tabSelect = 2;
                        switchFragment(mContent, mPenpalFragment, 2);
                        break;
                    case 4:
                        tabSelect = 3;
                        switchFragment(mContent, mUserFragment, 3);
                        break;
                }
            }
        });
        submitArticle.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                if (BuildConfig.IS_DEBUG) {
                    presenter.selectTypeFace(container);
                }
                return false;
            }
        });
        //动画
        rotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setDuration(1000);
        rotateAnimation.setFillAfter(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        bottomOption.setCurrentItem(tabSelect >= 2 ? tabSelect + 1 : tabSelect);
        if (getUserId() == 0) {
            bottomOption.setUnread(4, 0);
        } else {
            getMsgCount();
        }
    }

    @Override
    protected void initData() {
        if (UserInfoUtils.getUserInfo() != null) {
            presenter.GetUserQuiesceLogin();
        }
    }

    @Override
    protected void updateViews(boolean isRefresh) {
        getFirstLogInExp();
        getVersionUpdate();
    }

    /**
     * 新手引导提示
     */
    private void showNewbieGuide() {
        boolean firstEnter = SPUtils.getPreferences(SPKey.FIRST_ENTER_SHOW_NEWSGUIDE, true);
        if (firstEnter) {
            SPUtils.putPreferences(SPKey.FIRST_ENTER_SHOW_NEWSGUIDE, false);
            NewbieGuide.with(HomeActivity.this)
                    .setLabel("guide1")
                    .alwaysShow(true)
                    .addGuidePage(GuidePage.newInstance()
                            .addHighLight(bottomOption.getBottomItem(0).getImageView(), HighLight.Shape.CIRCLE)
                            .setLayoutRes(R.layout.view_guide_simple)).show();
        }
    }

    /**
     * 每日首次登陆APP获取经验
     */
    private void getFirstLogInExp() {
        //user_id
        int user_id = UserInfoUtils.getUserId();
        if (user_id == 0) {
            return;
        }
        //如果是每日第一次登录
        boolean isFirstLogin = UserInfoUtils.getFirstLoginExp();
        if (isFirstLogin) {
            map = new HashMap<>();
            map.put("user_id", user_id);
            presenter.getFirstLogInExp(user_id, Common.encryptionSign(map));
            map.clear();
        }
    }

    /**
     * 获取我的消息页面的未读信息数
     */
    public void getMsgCount() {
        //user_id
        int user_id = UserInfoUtils.getUserId();
        if (user_id == 0) {
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        presenter.getMsgCount(user_id, Common.encryptionSign(map));
        map.clear();
    }

    /**
     * app版本更新
     */
    public void getVersionUpdate() {
        map = new HashMap<>();
        map.put("type", 2);//1 ios,2 android
        map.put("version", ApkUtils.versionName(this));
        presenter.getVersionUpdate((int) map.get("type"),
                (String) map.get("version"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 当activity非正常销毁时会进入此方法中 保存一些临时性的数据
     */
    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        /**
         * 状态检测 用于内存不足的时候保证fragment不会重叠
         */
        loadFragment();
    }

    /**
     * 创建fragment
     */
    private void loadFragment() {
        sfm = getSupportFragmentManager();
        //推荐
        TodayRecommendFragment home = (TodayRecommendFragment) sfm.findFragmentByTag(tags[0]);
        mTodayRecommendFragment = home == null ? new TodayRecommendFragment() : home;
        //发现
        DiscoveryFragment discovery = (DiscoveryFragment) sfm.findFragmentByTag(tags[1]);
        mDiscoveryFragment = discovery == null ? new DiscoveryFragment() : discovery;
        //笔友会
        PenpalFragment penpal = (PenpalFragment) sfm.findFragmentByTag(tags[2]);
        mPenpalFragment = penpal == null ? new PenpalFragment() : penpal;
        //我
        UserInfoFragment userinfo = (UserInfoFragment) sfm.findFragmentByTag(tags[3]);
        mUserFragment = userinfo == null ? new UserInfoFragment() : userinfo;

        mContent = mTodayRecommendFragment;
        FragmentTransaction ft = sfm.beginTransaction();
        hideAllFragment(ft);
        if (!mContent.isAdded()) {
            ft.add(R.id.fl_container, mContent, tags[0]);
        }
        ft.show(mContent).commitAllowingStateLoss();
    }

    /**
     * fragment 切换
     *
     * @param from     当前fragment
     * @param to       目标fragment
     * @param position
     */
    public void switchFragment(BaseFragment from, BaseFragment to, int position) {
        if (mContent != to) {
            mContent = to;
            FragmentTransaction transaction = sfm.beginTransaction();
            if (!to.isAdded()) { // 先判断是否被add过
                transaction.add(R.id.fl_container, to, tags[position]);
                transaction.hide(from).show(to).commitAllowingStateLoss(); // 隐藏当前的fragment，add下一个到Activity中
                transaction.addToBackStack(tags[position]);
            } else {
                transaction.hide(from).show(to).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
            }
            if (position == 0) {
                bottomOption.getBottomItem(0).setText(isSmoothToSevenPage ? "刷新" : "推荐");
            } else {
                bottomOption.getBottomItem(0).setText("推荐");
            }
        } else {
            if (position == 0) {
                if (isSmoothToSevenPage) {
                    bottomOption.getBottomItem(0).getImageView().startAnimation(rotateAnimation);
                }
                ((TodayRecommendFragment) to).refreshTodayRecommend(false);
            }
        }
    }

    private void hideAllFragment(FragmentTransaction transaction) {
        if (mTodayRecommendFragment != null && !mTodayRecommendFragment.isHidden()) {
            transaction.hide(mTodayRecommendFragment);
        }
        if (mDiscoveryFragment != null && !mDiscoveryFragment.isHidden()) {
            transaction.hide(mDiscoveryFragment);
        }
        if (mPenpalFragment != null && !mPenpalFragment.isHidden()) {
            transaction.hide(mPenpalFragment);
        }
        if (mUserFragment != null && !mUserFragment.isHidden()) {
            transaction.hide(mUserFragment);
        }
    }

    // 第一次按下返回键的事件
    private long firstPressedTime;

    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - firstPressedTime < 2000) {
            int i = Process.myPid();
            Process.killProcess(i);
            System.exit(0);
        } else {
            toast("再按一次退出程序");
            firstPressedTime = System.currentTimeMillis();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtil.d("home ondestory");
        rotateAnimation.cancel();
        rotateAnimation = null;
        UMShareAPI.get(this).release();
        EventBus.getDefault().unregister(this);
        RichText.clear(this);
        RichText.recycle();
    }

    /**
     * 每日首次登陆APP获取经验
     *
     * @param bean
     */
    @Override
    public void onFirstLoginExp(INetBean bean) {
        if (bean.getErrCode() == 0) {
            UserInfoUtils.saveFirstLogInExp(false);
        }
    }

    @Override
    public void onMsgCount(MessageInfo info) {
        if (info.getErrCode() == 0) {
            MessageInfo.ResponseBean bean = info.getResponse();
            if (bean != null) {
                int sumMsgCount = bean.getAllMsgCount();
                if (sumMsgCount > 0) {
                    bottomOption.setUnread(4, sumMsgCount);//设置第4个页签显示提示的小红点
                } else {
                    bottomOption.setUnread(4, 0);//设置第4个页签显示提示的小红点
                }
            }
        }
    }

    /**
     * @param response 0.不可更新 1.强制更新 2.不强制更新
     */
    @Override
    public void onVersionUpdate(VersionUpdateResponse response) {
        if (response.getErrCode() == 0) {
            VersionUpdateResponse.ResponseBean bean = response.getResponse();
            if (bean == null) {
                return;
            }
            final int updateState = bean.getUpdateState();
            final String newVersion = bean.getNewVersion();
            if (newVersion.equals(ApkUtils.versionName(this)) || updateState == 1) {//版本相同或则强更，重置
                SPUtils.putPreferences(SPKey.VERSION_IS_HINT, 0);
            }
            int version_is_hint = SPUtils.getPreferences(SPKey.VERSION_IS_HINT, 0);
            if (version_is_hint == 1 && updateState != 1 || updateState == 0) {//不再提示后，是否出现了强更，或则直接不可更新reture
                showNewbieGuide();
                return;
            }
            if (updateState == 1 || updateState == 2) {
                String vsName = bean.getVsName();
                VersionUpdateDialog.Builder builder = new VersionUpdateDialog.Builder(this);
                builder.setVersionUpdateContent(vsName);
                if (updateState == 2) {
                    builder.setLeftHint("暂不升级");
                }
                builder.setRightHint("立即更新");
                final VersionUpdateDialog dialog = builder.create();
                dialog.setCanceledOnTouchOutside(false);
                dialog.setCancelable(false);
                dialog.show();
                builder.setListener(
                        new VersionUpdateDialog.Builder.OnClickListener() {
                            @Override
                            public void leftClickListener() {
                                dialog.dismiss();
                                if (updateState == 2) {//更新，方便不再提示
                                    SPUtils.putPreferences(SPKey.VERSION_IS_HINT, 1);
                                }
                            }

                            @Override
                            public void rightClickListener() {
                                Uri uri = Uri.parse(Common.TINY_DOWNLOAD);
                                startActivity(new Intent(Intent.ACTION_VIEW, uri));
                            }
                        });
            } else {
                showNewbieGuide();
            }
        } else {
            showNewbieGuide();
        }
    }

    /**
     * 接收推送消息
     */
    @Subscribe
    public void onJPushMessage(JPushMessage jPushMessage) {
        getMsgCount();
    }

    /**
     * 推荐底部icon实时替换
     *
     * @param iconReplace
     */
    @Subscribe
    public void onNavigationIconReplace(NavigationIconReplace iconReplace) {
        if (iconReplace == null || mContent != mTodayRecommendFragment) {
            return;
        }
        isSmoothToSevenPage = iconReplace.isSmoothToSevenPage();
        bottomOption.getBottomItem(0).setIconSelectedResourceId(isSmoothToSevenPage ?
                R.drawable.tab_home_selected_refresh_icon : R.drawable.tab_home_selected_icon);
        bottomOption.getBottomItem(0).setText(isSmoothToSevenPage ? "刷新" : "推荐");
    }
}